package mysqlCodeGen.gen.handler.impl;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import mysqlCodeGen.gen.handler.ReplaceHandler;
import mysqlCodeGen.gen.inner.Const;
import mysqlCodeGen.gen.inner.TableInfo;

import java.util.List;

/**
 * 替换处理器
 *
 * @author loser
 * @date 2023-01-06  12:20
 */
@AllArgsConstructor
public class XmlReplaceHandler implements ReplaceHandler {

    private String tableName;
    private String dbUrl;
    private String dbUser;
    private String dbPw;
    private String dbName;
    private String driver;

    @Override
    public List<String> work() {
        return buildForXml(new MysqlDataHandler(tableName, dbUrl, dbUser, dbPw, dbName, driver).searchByDb());
    }

    @Override
    public boolean match(String keyword) {
        return Const.FOR_XML.equals(keyword);
    }

    /**
     * 构建xml文件
     */
    private static List<String> buildForXml(List<TableInfo> tableInfos) {

        String frist = "";
        List<String> list = Lists.newArrayList();
        for (TableInfo tableInfo : tableInfos) {
            if (StrUtil.isNotBlank(tableInfo.getKeyType()) && "PRI".equals(tableInfo.getKeyType())) {
                frist = String.format(Const.FORMAT7, tableInfo.getCol(), getJdbcType(tableInfo.getDataType()), tableInfo.getName());
            } else {
                list.add(String.format(Const.FORMAT8, tableInfo.getCol(), getJdbcType(tableInfo.getDataType()), tableInfo.getName()));
            }
        }
        list.add(0, frist);
        return list;

    }

    /**
     * 将 数据库类型 转 为 mybatis 可以使用的类型
     */
    public static String getJdbcType(String type) {
        List<Pair<String, String>> pairs = Lists.newArrayList();
        pairs.add(new Pair<>("bigint", "BIGINT"));
        pairs.add(new Pair<>("int", "TINYINT"));
        pairs.add(new Pair<>("smallint", "TINYINT"));
        pairs.add(new Pair<>("varchar", "VARCHAR"));
        pairs.add(new Pair<>("datetime", "TIMESTAMP"));
        pairs.add(new Pair<>("double", "DOUBLE"));
        pairs.add(new Pair<>("text", "VARCHAR"));
        pairs.add(new Pair<>("bit", "BIT"));
        pairs.add(new Pair<>("tinyint", "BIT"));
        pairs.add(new Pair<>("timestamp", "TIMESTAMP"));
        for (Pair<String, String> pair : pairs) {
            if (pair.getKey().equals(type)) {
                return pair.getValue();
            }
        }
        return "";
    }

}
